package com.example.healkep;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.healkep.adapter.MyAdapter3;
import com.example.healkep.bean.ItemBean;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class FoodBaseAdapterActivity extends AppCompatActivity {

    private ListView mListView;
    private List<ItemBean> mBeanList;
    private MyAdapter3 mMyAdapter;
    String name;
    boolean foodbox, ingredientsbox, accessoriesbox;
    boolean flag;
    JSONArray jsonArray;
    int lastItem, startIndex=0, requestSize=15, scrollState, scrolledX, scrolledY;

    String introduction;
    String label;
    String cooking;
    String favor;
    String functions;
    String target;
    String disease;
    String constitution;
    String cuisine;
    String snack;
    String type;
    String kitchenware;
    String occasion;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1 && flag == true) {
                mBeanList = new ArrayList<>();
                JSONObject jsonObject = null;
                lastItem = startIndex + requestSize;
                if (jsonArray.length() < lastItem) lastItem = jsonArray.length();
                for (int i = startIndex; i < lastItem; i++) {
                    ItemBean newsBean = new ItemBean();
                    try {
                        jsonObject = jsonArray.getJSONObject(i);
                    newsBean.setTitle(/*jsonObject.getString("id") + */jsonObject.getString("name"));
                    newsBean.setContent("\ningredients: " + jsonObject.getString("ingredients"));
                    newsBean.setImgResId(R.drawable.test1);
                    mBeanList.add(newsBean);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                initEvent();
                if (lastItem >= jsonArray.length() && flag == true)
                {
                    Toast.makeText(FoodBaseAdapterActivity.this,"全部信息检索完毕!",Toast.LENGTH_LONG).show();
                    flag = false;
                }

                setListener();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (getSupportActionBar() != null){
            getSupportActionBar().hide();
        }   //隐藏标题栏
        super.onCreate(savedInstanceState);
        setContentView(R.layout.food_activity_base_adapter);

        name = (String) getIntent().getSerializableExtra("searchname");
        foodbox = (Boolean) getIntent().getSerializableExtra("foodbox");
        ingredientsbox = (Boolean) getIntent().getSerializableExtra("ingredientsbox");
        accessoriesbox = (Boolean) getIntent().getSerializableExtra("accessoriesbox");

        flag = true;

        mListView = findViewById(R.id.lv);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    FormBody.Builder params = new FormBody.Builder(); //建立
                    params.add("name", name);
                    OkHttpClient client = new OkHttpClient();
                    Request request = null;
                    if (foodbox) {
                        if (ingredientsbox) {
                            if (accessoriesbox)
                                request = new Request.Builder()
                                        .url(LoginActivity.url+"/food/login7")
                                        .post(params.build())
                                        .build();
                            else
                                request = new Request.Builder()
                                        .url(LoginActivity.url+"/food/login4")
                                        .post(params.build())
                                        .build();
                        } else {
                            if (accessoriesbox)
                                request = new Request.Builder()
                                        .url(LoginActivity.url+"/food/login5")
                                        .post(params.build())
                                        .build();
                            else
                                request = new Request.Builder()
                                        .url(LoginActivity.url+"/food/login1")
                                        .post(params.build())
                                        .build();
                        }
                    }
                    else {
                        if (ingredientsbox) {
                            if (accessoriesbox)
                                request = new Request.Builder()
                                        .url(LoginActivity.url+"/food/login6")
                                        .post(params.build())
                                        .build();
                            else
                                request = new Request.Builder()
                                        .url(LoginActivity.url+"/food/login2")
                                        .post(params.build())
                                        .build();
                        } else {
                            if (accessoriesbox)
                                request = new Request.Builder()
                                        .url(LoginActivity.url+"/food/login3")
                                        .post(params.build())
                                        .build();
                            else
                                request = new Request.Builder()
                                        .url(LoginActivity.url+"/food/login1")
                                        .post(params.build())
                                        .build();
                        }
                    }//选择接口
                    Response response = client.newCall(request).execute();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(FoodBaseAdapterActivity.this,"信息请求成功",Toast.LENGTH_LONG).show();
                        }
                    });
                    String responseData = response.body().string();  //将response转为string类型的responsedata
                    jsonArray = new JSONArray(responseData); //转换为json数组

                    Message msg = new Message();
                    msg.what = 1;
                    handler.sendMessage(msg);

                }catch (Exception e){
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(FoodBaseAdapterActivity.this,"网络连接失败！",Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }).start();
    }

    private void loadMoreData() {
        JSONObject jsonObject = null;
        lastItem = startIndex + requestSize;
        if (jsonArray.length() < lastItem) lastItem = jsonArray.length();
        for (int i = startIndex; i < lastItem; i++) {
            ItemBean newsBean = new ItemBean();
            try {
                jsonObject = jsonArray.getJSONObject(i);
                newsBean.setTitle(/*jsonObject.getString("id") + */jsonObject.getString("name"));
                newsBean.setContent("\ningredients: " + jsonObject.getString("ingredients"));
                newsBean.setImgResId(R.drawable.test1);
                mBeanList.add(newsBean);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        initEvent();
        if (lastItem >= jsonArray.length() && flag == true)
        {
            Toast.makeText(FoodBaseAdapterActivity.this,"全部信息检索完毕!",Toast.LENGTH_LONG).show();
            flag = false;
        }
    }

    private void setListener() {
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            int fVItem, vItemCount, tItemCount;
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                fVItem = firstVisibleItem;
                vItemCount = visibleItemCount;
                tItemCount = totalItemCount;
            }

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (fVItem > tItemCount - 7 && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && flag == true) {
                    Toast.makeText(FoodBaseAdapterActivity.this, "正在加载", Toast.LENGTH_LONG).show();
                    startIndex += requestSize;
                    scrolledX = view.getFirstVisiblePosition();
                    scrolledY = view.getChildAt(0).getTop();
                    loadMoreData();
                    mListView.setSelectionFromTop(scrolledX, scrolledY);
                }
            }//判断是否要加载新的信息
        });
    }

    private void initEvent() {
        mMyAdapter = new MyAdapter3(this,mBeanList);
        mListView.setAdapter(mMyAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ItemBean itemBean = mBeanList.get(position);
                String title = itemBean.getTitle();
                Intent intent = new Intent(FoodBaseAdapterActivity.this, FoodNewsDetailActivity.class);
                intent.putExtra("item",itemBean);
                try {
                    JSONObject jsonObject = jsonArray.getJSONObject(position);
                    introduction = jsonObject.getString("introduction");
                    label = jsonObject.getString("label");
                    cooking = jsonObject.getString("cooking");
                    favor = jsonObject.getString("favor");
                    functions = jsonObject.getString("functions");
                    target = jsonObject.getString("target");
                    disease = jsonObject.getString("disease");
                    constitution = jsonObject.getString("constitution");
                    cuisine = jsonObject.getString("cuisine");
                    snack = jsonObject.getString("snack");
                    type = jsonObject.getString("type");
                    kitchenware = jsonObject.getString("kitchenware");
                    occasion = jsonObject.getString("occasion");
                    if (jsonObject.getString("introduction") == "null") introduction = " ";
                    if (jsonObject.getString("label") == "null") label = " ";
                    if (jsonObject.getString("cooking") == "null") cooking = " ";
                    if (jsonObject.getString("favor") == "null") favor = " ";
                    if (jsonObject.getString("functions") == "null") functions = " ";
                    if (jsonObject.getString("target") == "null") target = " ";
                    if (jsonObject.getString("disease") == "null") disease = " ";
                    if (jsonObject.getString("constitution") == "null") constitution = " ";
                    if (jsonObject.getString("cuisine") == "null") cuisine = " ";
                    if (jsonObject.getString("snack") == "null") snack = " ";
                    if (jsonObject.getString("type") == "null") type = " ";
                    if (jsonObject.getString("kitchenware") == "null") kitchenware = " ";
                    if (jsonObject.getString("occasion") == "null") occasion = " ";
                    intent.putExtra("id",jsonObject.getString("id"));
                    intent.putExtra("name",jsonObject.getString("name"));
                    intent.putExtra("ingredients",jsonObject.getString("ingredients"));
                    intent.putExtra("accessories",jsonObject.getString("accessories"));
                    intent.putExtra("introduction",introduction);
                    intent.putExtra("label",label);
                    intent.putExtra("cooking",cooking);
                    intent.putExtra("favor",favor);
                    intent.putExtra("functions",functions);
                    intent.putExtra("target",target);
                    intent.putExtra("disease",disease);
                    intent.putExtra("constitution",constitution);
                    intent.putExtra("cuisine",cuisine);
                    intent.putExtra("snack",snack);
                    intent.putExtra("type",type);
                    intent.putExtra("kitchenware",kitchenware);
                    intent.putExtra("occasion",occasion);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                startActivity(intent);

                Toast.makeText(FoodBaseAdapterActivity.this, "你点击了" + title, Toast.LENGTH_SHORT).show();
            }
        });
        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

                return false;
            }
        });
    }
}